package com.ciwong.epaper.modules.epaper.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.TimeoutError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.bookstore.bean.PublishWorkContent;
import com.ciwong.epaper.modules.epaper.adapter.ChooseSentenceAdapter;
import com.ciwong.epaper.modules.epaper.bean.FollowreadTextParagraph;
import com.ciwong.epaper.modules.epaper.bean.FollowreadTextParagraphBean;
import com.ciwong.epaper.modules.epaper.bean.ResourceContent;
import com.ciwong.epaper.modules.epaper.bean.Sentences;
import com.ciwong.epaper.modules.epaper.dao.EpaperDao;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.widget.NoScrollListView;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.CWDialog;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:选择段落页面
 * @author: wyk
 * @time: 2021/5/19 17:00
 */
public class ChooseSentenceActivity extends BaseActivity {

    private ImageView work_sentence_go_back;
    //全选按钮
    private CheckBox choose_work_sentence;
    //选择跟读模式下拉框
    private Spinner choose_read_sentence_style;
    //选择跟读次数下拉框
    private Spinner choose_read_sentence_times;

    private NoScrollListView sentence_work_list_view;

    private TextView choose_sentence_detail_text;
    /**
     * 作业分数
     */
    private float workScore;

    private RelativeLayout choose_sentence_finish;
    //父目录versionId
    private String parentVersionId;

    private String versionId;
    //资源地址
    private String resourceUrl;
    //资源名
    private String resourceName;
    //资源详情
    private FollowreadTextParagraphBean followreadTextParagraphBean = new FollowreadTextParagraphBean();
    //段落集合
    private List<FollowreadTextParagraph> followReadWordDetailsList;

    //作业名
    private String workName;

    private int oldTime = 1;

    private ChooseSentenceAdapter chooseSentenceAdapter;
    //跟读次数
    private int readTime;
    //跟读方式 跟读 朗读 背诵
    private String readStyle;
    //是否选中
    private boolean isCheck;
    //资源内容
    private ResourceContent resourceContent;

    private int moduleId;

    private String resourceType;


    //句子数量
    private int sentenceCount;
    //总作业用时
    private double workLong;
    //选中作业用时
    private double chooseSentenceWorkLong;
    private String requirementContent;
    private TextView choose_sentence_work_long_text;

    @Override
    protected int setView() {
        return R.layout.activity_sentence_read;
    }

    @Override
    protected void findViews() {
        work_sentence_go_back = findViewById(R.id.work_sentence_go_back);
        choose_work_sentence = findViewById(R.id.choose_work_sentence);
        choose_read_sentence_style = findViewById(R.id.choose_read_sentence_style);
        choose_read_sentence_times = findViewById(R.id.choose_read_sentence_times);
        sentence_work_list_view = findViewById(R.id.sentence_work_list_view);
        choose_sentence_detail_text = findViewById(R.id.choose_sentence_detail_text);
        choose_sentence_finish = findViewById(R.id.choose_sentence_finish);
        choose_sentence_work_long_text = findViewById(R.id.choose_sentence_work_long_text);

        choose_sentence_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        work_sentence_go_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        choose_work_sentence.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (!compoundButton.isPressed()) {
                    return;
                }
                if (b) {
                    choose_work_sentence.setChecked(true);
                    choose_work_sentence.setSelected(true);
                    List<FollowreadTextParagraph> followReadWordDetailsList = followreadTextParagraphBean.getFollowReadWordDetailsList();
                    for (int i = 0; i < followReadWordDetailsList.size(); i++) {
                        followReadWordDetailsList.get(i).setChecked(true);
                    }
                    followreadTextParagraphBean.setCheckCount(sentenceCount);
                    setCheckStatus();
                    chooseSentenceAdapter.notifyDataSetChanged();
                } else {
                    choose_work_sentence.setChecked(false);
                    choose_work_sentence.setSelected(true);
                    List<FollowreadTextParagraph> followReadWordDetailsList = followreadTextParagraphBean.getFollowReadWordDetailsList();
                    for (int i = 0; i < followReadWordDetailsList.size(); i++) {
                        followReadWordDetailsList.get(i).setChecked(false);
                    }
                    followreadTextParagraphBean.setCheckCount(0);
                    choose_sentence_detail_text.setText("");
                    choose_sentence_work_long_text.setText("");
                    chooseSentenceAdapter.notifyDataSetChanged();
                }
            }
        });

        choose_read_sentence_style.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String[] stringArray = ChooseSentenceActivity.this.getResources().getStringArray(R.array.sentence_read_style);
                readStyle = stringArray[i];
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        choose_read_sentence_times.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                readTime = i + 1;
                chooseSentenceWorkLong = chooseSentenceWorkLong / oldTime * readTime;
                workLong = workLong / oldTime * readTime;
                oldTime = readTime;
                int workRefLong = (int) (Math.ceil(chooseSentenceWorkLong / 60));
                if (null != followreadTextParagraphBean) {
                    SpannableStringBuilder chooseCountText = new SpannableStringBuilder("已选择 " + followreadTextParagraphBean.getCheckCount() + " 个段落");
                    SpannableStringBuilder chooseWorkLongText = new SpannableStringBuilder("预计 " + workRefLong + " 分钟");
                    ForegroundColorSpan GreenSpan = new ForegroundColorSpan(Color.parseColor("#5ce191"));

                    if (followreadTextParagraphBean.getCheckCount() < 10) {
                        chooseCountText.setSpan(GreenSpan, 4, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    } else {
                        chooseCountText.setSpan(GreenSpan, 4, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }

                    if (workRefLong >= 100) {
                        chooseWorkLongText.setSpan(GreenSpan, 3, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    } else if (workRefLong < 10) {
                        chooseWorkLongText.setSpan(GreenSpan, 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    } else {
                        chooseWorkLongText.setSpan(GreenSpan, 3, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }
                    choose_sentence_detail_text.setText(chooseCountText);
                    choose_sentence_work_long_text.setText(chooseWorkLongText);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void init() {
        hideTitleBar();
        Intent intent = getIntent();
        versionId = intent.getStringExtra(IntentFlag.INTENT_FLAG_VERSION_ID);
        parentVersionId = intent.getStringExtra(IntentFlag.INTENT_FLAG_PARENT_VERSION_ID);
        resourceName = intent.getStringExtra(IntentFlag.INTENT_FLAG_RESOURCE_NAME);
        resourceUrl = intent.getStringExtra(IntentFlag.INTENT_FLAG_RESOURCE_URL);
        requirementContent = intent.getStringExtra(IntentFlag.INTENT_FLAG_READ_TIME);
        workLong = intent.getIntExtra(IntentFlag.INTENT_FLAG_WORK_LONG, 0);
        isCheck = intent.getBooleanExtra(IntentFlag.INTENT_FLAG_BOOLEAN, false);
        moduleId = intent.getIntExtra(IntentFlag.INTENT_FLAG_MODULE_ID, 0);
        workName = intent.getStringExtra(IntentFlag.INTENT_FLAG_WORK_NAME);
        resourceType = intent.getStringExtra(IntentFlag.INTENT_FLAG_RESOURCE_TYPE);
        if (null != requirementContent && !"".equals(requirementContent)) {
            JSONObject jsonObject = JSONObject.parseObject(requirementContent);
            oldTime = jsonObject.getIntValue("readtimes");
        }
        choose_read_sentence_times.setSelection(oldTime - 1);
        followreadTextParagraphBean = (FollowreadTextParagraphBean) intent.getSerializableExtra(IntentFlag.INTENT_FLAG_OBJ);
        showGetPermissDialog();
        if (null != followreadTextParagraphBean) {
            chooseSentenceAdapter = new ChooseSentenceAdapter(ChooseSentenceActivity.this, followreadTextParagraphBean);
            sentence_work_list_view.setAdapter(chooseSentenceAdapter);
        }

    }

    private final int CODE_REQUEST_WRITESD_PERMISSION = 8800;

    private CWDialog getSDcardPermissDialog;

    /**
     * 获取SDcard权限提示框
     */
    private boolean showGetPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            checkSDcardpermiss();
        } else {
            if (getSDcardPermissDialog == null) {
                getSDcardPermissDialog = new CWDialog(this);
                getSDcardPermissDialog.setTitle(R.string.get_permiss_title);
                getSDcardPermissDialog.setTitleTextColor(Color.BLACK);
                getSDcardPermissDialog.setMessage(getString(R.string.get_sdcard_permiss_content_audio), 16, Color.BLACK, Gravity.LEFT);
                getSDcardPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                        checkSDcardpermiss();
                    }
                });
                getSDcardPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                    }
                });
            }
            getSDcardPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用sd卡，判断权限
     */
    private boolean checkSDcardpermiss() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, getString(R.string.read_and_write_local_storage_permissions));
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_WRITESD_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                //initDataView();
                            } else {
                                //ToastUtil.INSTANCE.toastCenterError(R.string);
                            }
                        }
                    });
        } else {
            //initDataView();
        }
        return true;
    }


    public void setCheckStatus() {
        chooseSentenceWorkLong = workLong / sentenceCount * followreadTextParagraphBean.getCheckCount();
        //向上取整
        int workRefLong = ((int) (Math.ceil(chooseSentenceWorkLong / 60)));
        SpannableStringBuilder chooseCountText = new SpannableStringBuilder("已选择 " + followreadTextParagraphBean.getCheckCount() + " 个段落");
        SpannableStringBuilder chooseWorkLongText = new SpannableStringBuilder("预计 " + (int) workRefLong + " 分钟");
        ForegroundColorSpan GreenSpan = new ForegroundColorSpan(Color.parseColor("#5ce191"));

        if (followreadTextParagraphBean.getCheckCount() < 10) {
            chooseCountText.setSpan(GreenSpan, 4, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            chooseCountText.setSpan(GreenSpan, 4, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        if (workRefLong >= 100) {
            chooseWorkLongText.setSpan(GreenSpan, 3, 6, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else if (workRefLong < 10) {
            chooseWorkLongText.setSpan(GreenSpan, 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            chooseWorkLongText.setSpan(GreenSpan, 3, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        choose_sentence_detail_text.setText(chooseCountText);
        choose_sentence_work_long_text.setText(chooseWorkLongText);
        if (sentenceCount == followreadTextParagraphBean.getCheckCount()) {
            choose_work_sentence.setChecked(true);
            choose_work_sentence.setSelected(true);
        } else if (0 == followreadTextParagraphBean.getCheckCount()) {
            choose_work_sentence.setChecked(false);
            choose_work_sentence.setSelected(true);
        } else {
            choose_work_sentence.setChecked(true);
            choose_work_sentence.setSelected(false);
        }

    }

    @Override
    protected void loadData() {
        if (null != followreadTextParagraphBean && null != followreadTextParagraphBean.getFollowReadWordDetailsList() && 0 != followreadTextParagraphBean.getCheckCount()) {
            sentenceCount = followreadTextParagraphBean.getFollowReadWordDetailsList().size();
            setCheckStatus();
            chooseSentenceAdapter.notifyDataSetChanged();
        } else {
            showCricleProgress();
            getResourceStatisticsWeb(parentVersionId, versionId, moduleId, resourceType);
        }

    }

    private void followreadTextParagraph(String versionid) {
        EpaperDao.getInstance().followreadTextParagraph(versionId, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                hideCricleProgress();
                if (data instanceof TimeoutError) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                } else {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_try_later));
                }
            }

            @Override
            public void failed(Object data) {
                hideCricleProgress();
                if (data instanceof TimeoutError) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                } else {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_try_later));
                }
            }

            @Override
            public void success(Object data) {
                hideCricleProgress();
                if (null != data) {
                    followReadWordDetailsList = (List<FollowreadTextParagraph>) data;
                    sentenceCount = followReadWordDetailsList.size();
                    followreadTextParagraphBean = new FollowreadTextParagraphBean();
                    followreadTextParagraphBean.setFollowReadWordDetailsList(followReadWordDetailsList);
                    double sentenceTime;
                    sentenceTime = 0 == resourceContent.getDefAnswerTime() ? 30 : resourceContent.getDefAnswerTime();
                    workLong = ((int) (Math.ceil(sentenceTime * resourceContent.getSentenceCount())));
                    if (isCheck) {
                        followreadTextParagraphBean.setCheckCount(sentenceCount);
                    } else {
                        followreadTextParagraphBean.setCheckCount(0);
                    }
                    setCheckStatus();
                    chooseSentenceAdapter = new ChooseSentenceAdapter(ChooseSentenceActivity.this, followreadTextParagraphBean);
                    sentence_work_list_view.setAdapter(chooseSentenceAdapter);
                    //chooseSentenceAdapter.notifyDataSetChanged();
                }
            }
        });
    }


    /**
     * 获取资源内容统计信息
     *
     * @param parentVersionId
     * @param versionId
     * @param moduleId
     * @param resourceType    资源类型
     */
    public void getResourceStatisticsWeb(String parentVersionId, final String versionId, int moduleId, final String resourceType) {

        EpaperDao.getInstance().getResourceStatisticsWeb(parentVersionId, versionId, moduleId, resourceType, new BaseExtCallBack(ChooseSentenceActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                hideCricleProgress();
                if (data instanceof TimeoutError) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                }
            }

            @Override
            public void failed(Object data) {
                hideCricleProgress();
                if (!NetworkUtils.isOnline()) {
                    ToastUtil.INSTANCE.toastCenterError(getString(R.string.load_faild_check_net_work));
                    return;
                }
            }

            @Override
            public void success(Object data) {
                if (null != data) {
                    resourceContent = (ResourceContent) data;
                    workScore = resourceContent.getRefScore();
                    //句子跟读
                    followreadTextParagraph(versionId);
                }
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e("MediaPlayer ", "停止播放");
        chooseSentenceAdapter.stopPlaySentence();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        /*handler.removeCallbacks(startRunnable);
        handler.removeCallbacks(stopRunnable);*/
        chooseSentenceAdapter.stopPlaySentence();

    }

    @Override
    public void finish() {
        chooseSentenceAdapter.stopPlaySentence();
        setChooseSentence();
        super.finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            setChooseSentence();
            finish();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    public void setChooseSentence() {
        StringBuffer str = new StringBuffer();
        if (null != followreadTextParagraphBean) {
            int checkCount = followreadTextParagraphBean.getCheckCount();
            List<FollowreadTextParagraph> followReadWordDetailsList = followreadTextParagraphBean.getFollowReadWordDetailsList();
            if (checkCount == followReadWordDetailsList.size()) {
                for (int i = 0; i < followReadWordDetailsList.size(); i++) {
                    List<Sentences> sentencesList = followReadWordDetailsList.get(i).getSentences();
                    for (int a = 0; a < sentencesList.size(); a++) {
                        if (str.length() == 0 || "".equals(str)) {
                            str.append(followReadWordDetailsList.get(i).getSentences().get(a).getVersionId());
                        } else {
                            str.append("," + followReadWordDetailsList.get(i).getSentences().get(a).getVersionId());
                        }
                    }

                }
            } else {
                for (int i = 0; i < followReadWordDetailsList.size(); i++) {
                    if (null != followReadWordDetailsList.get(i).getChecked() && followReadWordDetailsList.get(i).getChecked()) {
                        List<Sentences> sentencesList = followReadWordDetailsList.get(i).getSentences();
                        for (int a = 0; a < sentencesList.size(); a++) {
                            if (str.length() == 0 || "".equals(str)) {
                                str.append(followReadWordDetailsList.get(i).getSentences().get(a).getVersionId());
                            } else {
                                str.append("," + followReadWordDetailsList.get(i).getSentences().get(a).getVersionId());
                            }
                        }
                    }
                }
            }
            JSONObject jsonObject = new JSONObject();
            //作业要求
            jsonObject.put("readtimes", readTime);
            if (readStyle.equals("跟读")) {
                jsonObject.put("speekingtype", 1);
            } else if (readStyle.equals("朗读")) {
                jsonObject.put("speekingtype", 2);
            } else {
                jsonObject.put("speekingtype", 3);
            }
            PublishWorkContent publishWorkContent = new PublishWorkContent();
            publishWorkContent.setCheckedResource(str.toString());
            publishWorkContent.setTotalQuesNum(checkCount);
            publishWorkContent.setRequirementContent(jsonObject.toString());
            publishWorkContent.setRefLong((int) chooseSentenceWorkLong);
            publishWorkContent.setTotalWorkLong((int) workLong);
            publishWorkContent.setFollowreadTextParagraphBean(followreadTextParagraphBean);
            publishWorkContent.setModuleId(moduleId);
            publishWorkContent.setParentVersionId(parentVersionId);
            publishWorkContent.setVersionId(versionId);
            publishWorkContent.setWorkName(workName);
            publishWorkContent.setWorkScore(workScore);
            publishWorkContent.setResourceName(resourceName);
            publishWorkContent.setResourceType(resourceType);
            publishWorkContent.setResourceUrl(resourceUrl);

            Intent intent = new Intent();
            intent.putExtra(IntentFlag.INTENT_FLAG_WORD_DETAILS, str.toString());
            intent.putExtra(IntentFlag.INTENT_FLAG_RESOURCE_NAME, resourceName);
            intent.putExtra(IntentFlag.INTENT_FLAG_RESOURCE_URL, resourceUrl);
            intent.putExtra(IntentFlag.INTENT_FLAG_VERSION_ID, versionId);
            intent.putExtra(IntentFlag.INTENT_FLAG_JSONOBJECT, jsonObject.toString());
            intent.putExtra(IntentFlag.INTENT_FLAG_OBJ, (Serializable) followreadTextParagraphBean);
            intent.putExtra(IntentFlag.INTENT_FLAG_WORK_LONG, (int) chooseSentenceWorkLong);
            intent.putExtra(IntentFlag.INTENT_FLAG_WORK_CONTENT, publishWorkContent);
            setResult(RESULT_OK, intent);
        }
    }


}
